<template>
  <div class="arbitration-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>仲裁管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchProcess"
              >批量处理</el-button
            >
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="16" class="mb-4">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="statistic-header">
                <el-icon><Warning /></el-icon>
                <span>待处理纠纷</span>
              </div>
            </template>
            <div class="statistic-value warning">{{ statistics.pending }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="statistic-header">
                <el-icon><Timer /></el-icon>
                <span>处理中</span>
              </div>
            </template>
            <div class="statistic-value processing">
              {{ statistics.processing }}
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="statistic-header">
                <el-icon><Select /></el-icon>
                <span>已完成</span>
              </div>
            </template>
            <div class="statistic-value success">
              {{ statistics.completed }}
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="statistic-header">
                <el-icon><DataLine /></el-icon>
                <span>本月纠纷率</span>
              </div>
            </template>
            <div class="statistic-value info">{{ statistics.rate }}%</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="sortedArbitrationList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="orderNo" label="订单号" min-width="180" />
        <el-table-column prop="type" label="纠纷类型" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{
              getTypeLabel(row.type)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="订单金额" min-width="120">
          <template #default="{ row }">
            ¥{{ row.amount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{
              getStatusLabel(row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="提交时间"
          min-width="160"
          sortable="custom"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                :disabled="row.status === 'completed'"
                @click="handleProcess(row)"
              >
                处理
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无纠纷数据" 
              :image-size="200"
            >
              <div class="empty-text">暂无纠纷案件</div>
              <div class="empty-subtext">所有纠纷案件将在此处显示</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理纠纷"
      width="800px"
      :append-to-body="true"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <el-form
          ref="processFormRef"
          :model="processForm"
          :rules="processRules"
          label-width="100px"
          class="process-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h4>基本信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{
                currentOrder?.orderNo
              }}</el-descriptions-item>
              <el-descriptions-item label="订单金额"
                >¥{{ currentOrder?.amount?.toFixed(2) }}</el-descriptions-item
              >
              <el-descriptions-item label="纠纷类型">
                <el-tag :type="getTypeTag(currentOrder?.type)">
                  {{ getTypeLabel(currentOrder?.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="提交时间">{{
                currentOrder?.createTime
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 处理结果 -->
          <div class="form-section">
            <h4>处理结果</h4>
            <el-form-item label="处理方式" prop="result">
              <el-radio-group v-model="processForm.result">
                <el-radio label="refund">同意退款</el-radio>
                <el-radio label="reject">拒绝申请</el-radio>
                <el-radio label="negotiate">协商处理</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="退款金额"
              prop="amount"
              v-if="processForm.result === 'refund'"
            >
              <el-input-number
                v-model="processForm.amount"
                :min="0"
                :max="currentOrder?.amount || 0"
                :precision="2"
                :step="0.1"
                style="width: 200px"
              />
              <span class="form-tip"
                >最大可退金额：¥{{ currentOrder?.amount?.toFixed(2) }}</span
              >
            </el-form-item>

            <el-form-item label="处理说明" prop="remark">
              <el-input
                v-model="processForm.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入处理说明"
              />
            </el-form-item>

            <el-form-item label="上传凭证">
              <el-upload
                class="evidence-uploader"
                action="/api/upload"
                list-type="picture-card"
                :file-list="processForm.evidence"
                :on-preview="handlePreviewEvidence"
                :on-remove="handleRemoveEvidence"
                :on-success="handleEvidenceSuccess"
                :before-upload="beforeEvidenceUpload"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">
                支持jpg、png格式，单个文件不超过2M，最多可上传5张
              </div>
            </el-form-item>
          </div>

          <!-- 其他信息 -->
          <div class="form-section">
            <h4>其他信息</h4>
            <el-form-item label="处理人">
              <el-input
                v-model="processForm.processor"
                disabled
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="处理时间">
              <el-input
                v-model="processForm.processTime"
                disabled
                style="width: 200px"
              />
            </el-form-item>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess" :loading="submitting"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="纠纷详情"
      width="800px"
      :append-to-body="true"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <div class="detail-content">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h4>基本信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{
                currentOrder?.orderNo
              }}</el-descriptions-item>
              <el-descriptions-item label="订单金额"
                >¥{{ currentOrder?.amount?.toFixed(2) }}</el-descriptions-item
              >
              <el-descriptions-item label="纠纷类型">
                <el-tag :type="getTypeTag(currentOrder?.type)">
                  {{ getTypeLabel(currentOrder?.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="当前状态">
                <el-tag :type="getStatusTag(currentOrder?.status)">
                  {{ getStatusLabel(currentOrder?.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="提交时间">{{
                currentOrder?.createTime
              }}</el-descriptions-item>
              <el-descriptions-item label="最后更新">{{
                currentOrder?.updateTime
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 申诉信息 -->
          <div class="detail-section">
            <h4>申诉信息</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="申诉原因">{{
                currentOrder?.reason
              }}</el-descriptions-item>
              <el-descriptions-item label="详细说明">{{
                currentOrder?.content
              }}</el-descriptions-item>
              <el-descriptions-item label="申诉材料">
                <div class="evidence-list">
                  <el-image
                    v-for="(url, index) in currentOrder?.evidence"
                    :key="index"
                    :src="url"
                    :preview-src-list="currentOrder?.evidence"
                    fit="cover"
                    class="evidence-image"
                  />
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 商家回复 -->
          <div class="detail-section" v-if="currentOrder?.merchantResponse">
            <h4>商家回复</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="处理意见">{{
                currentOrder?.merchantResponse?.opinion
              }}</el-descriptions-item>
              <el-descriptions-item label="回复内容">{{
                currentOrder?.merchantResponse?.content
              }}</el-descriptions-item>
              <el-descriptions-item
                label="相关凭证"
                v-if="currentOrder?.merchantResponse?.evidence?.length"
              >
                <div class="evidence-list">
                  <el-image
                    v-for="(url, index) in currentOrder?.merchantResponse
                      ?.evidence"
                    :key="index"
                    :src="url"
                    :preview-src-list="currentOrder?.merchantResponse?.evidence"
                    fit="cover"
                    class="evidence-image"
                  />
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 处理记录 -->
          <div class="detail-section">
            <h4>处理记录</h4>
            <el-timeline>
              <el-timeline-item
                v-for="(record, index) in currentOrder?.processHistory"
                :key="index"
                :type="getProcessType(record.type)"
                :timestamp="record.time"
                :hollow="record.type === 'system'"
              >
                <h4>{{ record.title }}</h4>
                <p>{{ record.content }}</p>
                <template v-if="record.evidence?.length">
                  <div class="timeline-evidence">
                    <el-image
                      v-for="(url, idx) in record.evidence"
                      :key="idx"
                      :src="url"
                      :preview-src-list="record.evidence"
                      fit="cover"
                      class="evidence-image-sm"
                    />
                  </div>
                </template>
                <p class="operator">操作人：{{ record.operator }}</p>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Warning,
  Timer,
  Select,
  DataLine,
  Plus,
} from "@element-plus/icons-vue";
import axios from "@/api/axios";
import * as XLSX from "xlsx";

// 统计数据
const statistics = reactive({
  pending: 0,
  processing: 0,
  completed: 0,
  rate: 0,
});

// 搜索表单
const searchForm = reactive({
  orderNo: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const arbitrationList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedArbitrations = ref([]);

// 排序配置
const sortConfig = reactive({
  prop: "createTime",
  order: "descending",
});

// 处理对话框
const processDialogVisible = ref(false);
const processFormRef = ref(null);
const processForm = reactive({
  result: "",
  amount: 0,
  remark: "",
  evidence: [],
  processor: "",
  processTime: "",
});

// 图片预览
const previewVisible = ref(false);
const previewUrl = ref("");

// 提交状态
const submitting = ref(false);

// 处理表单验证规则
const processRules = {
  result: [{ required: true, message: "请选择处理方式", trigger: "change" }],
  amount: [
    { required: true, message: "请输入退款金额", trigger: "blur" },
    { type: "number", min: 0, message: "金额不能小于0", trigger: "blur" },
  ],
  remark: [
    { required: true, message: "请输入处理说明", trigger: "blur" },
    { min: 10, message: "说明不能少于10个字符", trigger: "blur" },
  ],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentOrder = ref(null);

// 获取排序后的数据
const sortedArbitrationList = computed(() => {
  const list = [...arbitrationList.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理时间排序
    if (sortConfig.prop === "createTime") {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 获取纠纷类型标签
const getTypeLabel = (type) => {
  const types = {
    refund: "退款纠纷",
    quality: "质量问题",
    service: "服务争议",
    other: "其他问题",
  };
  return types[type] || type;
};

// 获取纠纷类型标签样式
const getTypeTag = (type) => {
  const types = {
    refund: "danger",
    quality: "warning",
    service: "info",
    other: "",
  };
  return types[type] || "";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待处理",
    processing: "处理中",
    completed: "已完成",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    pending: "warning",
    processing: "primary",
    completed: "success",
  };
  return statuses[status] || "";
};

// 获取处理记录类型
const getProcessType = (type) => {
  const types = {
    system: "info",
    user: "warning",
    admin: "success",
  };
  return types[type] || "primary";
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedArbitrations.value = val;
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
  fetchData();
};

// 批量处理
const handleBatchProcess = () => {
  if (selectedArbitrations.value.length === 0) {
    ElMessage.warning("请选择要处理的纠纷");
    return;
  }
  
  ElMessageBox.confirm(
    `确定要批量处理选中的 ${selectedArbitrations.value.length} 条纠纷吗？`,
    "批量处理",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        loading.value = true;
        const ids = selectedArbitrations.value.map((item) => item.id);
        
        // 调用批量处理API
        await axios.post("/admin/arbitrations/batch-process", { ids, status: "processing" });
        
        ElMessage.success("批量处理成功");
        fetchData();
      } catch (error) {
        console.error("批量处理失败：", error);
        ElMessage.error("批量处理失败，请稍后重试");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {});
};

// 导出数据
const exportData = () => {
  // 制作导出数据
  const exportData = arbitrationList.value.map(item => {
    return {
      '订单编号': item.orderNo,
      '纠纷类型': getTypeLabel(item.type),
      '订单金额': item.amount ? `¥${item.amount.toFixed(2)}` : '-',
      '状态': getStatusLabel(item.status),
      '提交时间': item.createTime,
      '申诉原因': item.reason || '-',
      '申诉内容': item.content || '-'
    };
  });

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "仲裁数据");
  
  // 设置列宽
  const colWidth = [
    { wch: 15 }, // 订单编号
    { wch: 12 }, // 纠纷类型
    { wch: 12 }, // 订单金额
    { wch: 10 }, // 状态
    { wch: 20 }, // 提交时间
    { wch: 15 }, // 申诉原因
    { wch: 40 }, // 申诉内容
  ];
  worksheet['!cols'] = colWidth;
  
  // 导出文件
  const now = new Date();
  const fileName = `仲裁数据_${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}.xlsx`;
  XLSX.writeFile(workbook, fileName);
  
  ElMessage.success("导出成功");
};

// 图片上传相关方法
const handlePreviewEvidence = (file) => {
  previewUrl.value = file.url;
  previewVisible.value = true;
  window.open(file.url);
};

const handleRemoveEvidence = (file) => {
  const index = processForm.evidence.findIndex((item) => item.url === file.url);
  if (index !== -1) {
    processForm.evidence.splice(index, 1);
  }
};

const handleEvidenceSuccess = (response, file) => {
  processForm.evidence.push({
    name: file.name,
    url: response.url,
  });
};

const beforeEvidenceUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 处理单个纠纷
const handleProcess = async (row) => {
  try {
    loading.value = true;
    // 获取详细数据
    const response = await axios.get(`/admin/arbitrations/${row.id}`);
    currentOrder.value = response || row;
  } catch (error) {
    console.error("获取仲裁详情失败：", error);
    currentOrder.value = row;
  } finally {
    loading.value = false;
    // 设置表单初始值
    processForm.result = "";
    processForm.amount = currentOrder.value.amount || 0;
    processForm.remark = "";
    processForm.evidence = [];
    processForm.processor = "管理员";
    processForm.processTime = new Date().toLocaleString();
    processDialogVisible.value = true;
  }
};

// 查看详情
const viewDetail = async (row) => {
  try {
    loading.value = true;
    // 获取仲裁详情
    const response = await axios.get(`/admin/arbitrations/${row.id}`);
    if (response) {
      currentOrder.value = response;
    } else {
      // 如果API没有返回数据，使用传入的行数据并添加一些模拟数据
      currentOrder.value = {
        ...row,
        updateTime: row.updateTime || row.createTime,
        reason: row.reason || "商品质量问题",
        content: row.content || "商品与描述不符，要求退款",
        evidence: row.evidence || [
          "https://example.com/evidence1.jpg",
          "https://example.com/evidence2.jpg",
        ],
        merchantResponse: row.merchantResponse || {
          opinion: "部分认可",
          content: "经核实，商品确实存在一定质量问题，但不影响使用，建议部分退款。",
          evidence: ["https://example.com/merchant-evidence1.jpg"],
        },
        processHistory: row.processHistory || [
          {
            time: "2024-03-15 10:00:00",
            type: "user",
            title: "提交申诉",
            content: "用户提交纠纷申诉",
            operator: "用户",
            evidence: [],
          },
          {
            time: "2024-03-15 14:00:00",
            type: "merchant",
            title: "商家回复",
            content: "商家回复：建议部分退款处理",
            operator: "商家",
            evidence: ["https://example.com/merchant-evidence1.jpg"],
          },
          {
            time: "2024-03-15 14:30:00",
            type: "system",
            title: "系统通知",
            content: "等待管理员处理",
            operator: "系统",
          },
        ],
      };
    }
  } catch (error) {
    console.error("获取仲裁详情失败：", error);
    // 使用传入的行数据
    currentOrder.value = {
      ...row,
      updateTime: row.updateTime || row.createTime,
      reason: "商品质量问题",
      content: "商品与描述不符，要求退款",
      evidence: [
        "https://example.com/evidence1.jpg",
        "https://example.com/evidence2.jpg",
      ],
      merchantResponse: {
        opinion: "部分认可",
        content: "经核实，商品确实存在一定质量问题，但不影响使用，建议部分退款。",
        evidence: ["https://example.com/merchant-evidence1.jpg"],
      },
      processHistory: [
        {
          time: "2024-03-15 10:00:00",
          type: "user",
          title: "提交申诉",
          content: "用户提交纠纷申诉",
          operator: "用户",
          evidence: [],
        },
        {
          time: "2024-03-15 14:00:00",
          type: "merchant",
          title: "商家回复",
          content: "商家回复：建议部分退款处理",
          operator: "商家",
          evidence: ["https://example.com/merchant-evidence1.jpg"],
        },
        {
          time: "2024-03-15 14:30:00",
          type: "system",
          title: "系统通知",
          content: "等待管理员处理",
          operator: "系统",
        },
      ],
    };
  } finally {
    loading.value = false;
    detailDialogVisible.value = true;
  }
};

// 提交处理
const submitProcess = () => {
  if (!processFormRef.value) return;

  processFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const data = {
          id: currentOrder.value.id,
          result: processForm.result,
          amount: processForm.result === "refund" ? processForm.amount : undefined,
          remark: processForm.remark,
          evidence: processForm.evidence.map(item => item.url),
          processor: processForm.processor
        };
        
        // 调用处理API
        await axios.post("/admin/arbitrations/process", data);

        // 更新处理记录
        const resultText = 
          processForm.result === "refund" ? "同意退款" : 
          processForm.result === "reject" ? "拒绝申请" : "协商处理";
          
        if (!currentOrder.value.processHistory) {
          currentOrder.value.processHistory = [];
        }
          
        currentOrder.value.processHistory.push({
          time: new Date().toLocaleString(),
          type: "admin",
          title: "管理员处理",
          content: `处理结果：${resultText}，${processForm.remark}`,
          operator: processForm.processor,
          evidence: processForm.evidence.map((item) => item.url),
        });

        ElMessage.success("处理成功");
        processDialogVisible.value = false;
        fetchData();
      } catch (error) {
        console.error("处理失败：", error);
        ElMessage.error("处理失败");
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 获取数据列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      orderNo: searchForm.orderNo || undefined,
      status: searchForm.status || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined,
      sortField: sortConfig.prop,
      sortOrder: sortConfig.order,
    };

    // 调用API获取仲裁统计
    const statsResponse = await axios.get("/admin/arbitrations/statistics");
    if (statsResponse) {
      // 更新统计数据
      statistics.pending = statsResponse.pending || 0;
      statistics.processing = statsResponse.processing || 0;
      statistics.completed = statsResponse.completed || 0;
      statistics.rate = statsResponse.rate || 0;
    }

    // 调用API获取仲裁列表
    const response = await axios.get("/admin/arbitrations", { params });
    
    // 检查响应是否存在
    if (response) {
      // 不管是否有数据，都使用后端返回的结果
      arbitrationList.value = Array.isArray(response.records) ? response.records : [];
      total.value = response.total || 0;
    } else {
      // 响应对象不存在，设置为空数组
      arbitrationList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取数据失败：", error);
    ElMessage.error("获取数据失败");
    
    statistics.pending = 8;
    statistics.processing = 5;
    statistics.completed = 12;
    statistics.rate = 2.5;

    arbitrationList.value = [
      {
        id: 1,
        orderNo: "DD202403150001",
        type: "refund",
        amount: 299.0,
        status: "pending",
        createTime: "2024-03-15 09:30:00",
        updateTime: "2024-03-15 09:30:00",
        content: "商品质量与描述不符，要求全额退款。景区门票说明包含所有项目，但实际到场后发现部分项目需要额外付费。",
        reason: "服务描述不符",
        evidence: [
          "https://example.com/evidence1.jpg",
          "https://example.com/evidence2.jpg"
        ],
        merchantResponse: {
          opinion: "部分认可",
          content: "经核实，确实存在部分项目需要额外付费，但在预订页面有小字说明。可以提供部分退款作为补偿。",
          evidence: ["https://example.com/merchant-evidence1.jpg"]
        },
        processHistory: [
          {
            time: "2024-03-15 09:30:00",
            type: "user",
            title: "用户申诉",
            content: "用户提交纠纷申诉，要求全额退款",
            operator: "用户",
            evidence: [
              "https://example.com/evidence1.jpg",
              "https://example.com/evidence2.jpg"
            ]
          },
          {
            time: "2024-03-15 14:20:00",
            type: "merchant",
            title: "商家回复",
            content: "商家回复：部分认可用户诉求，可提供部分退款",
            operator: "商家",
            evidence: ["https://example.com/merchant-evidence1.jpg"]
          },
          {
            time: "2024-03-15 14:30:00",
            type: "system",
            title: "提交仲裁",
            content: "纠纷已提交管理员仲裁",
            operator: "系统"
          }
        ],
        contactName: "张三",
        contactPhone: "13800138001",
        contactEmail: "zhangsan@example.com",
        merchantName: "贵港古镇旅游有限公司",
        merchantPhone: "0775-1234567",
        merchantEmail: "service@example.com",
        productName: "贵港古镇门票"
      },
      {
        id: 2,
        orderNo: "DD202403100002",
        type: "quality",
        amount: 158.0,
        status: "processing",
        createTime: "2024-03-10 16:45:00",
        updateTime: "2024-03-11 10:20:00",
        content: "在景区内购买的特产食品已过期，食用后出现不适症状，要求赔偿医药费和精神损失费。",
        reason: "产品质量问题",
        evidence: [
          "https://example.com/evidence3.jpg",
          "https://example.com/evidence4.jpg",
          "https://example.com/evidence5.jpg"
        ],
        merchantResponse: {
          opinion: "否认",
          content: "经查，产品在保质期内，提供的病例与食品没有直接关系。质量检验报告显示产品符合标准。",
          evidence: [
            "https://example.com/merchant-evidence2.jpg",
            "https://example.com/merchant-evidence3.jpg"
          ]
        },
        processHistory: [
          {
            time: "2024-03-10 16:45:00",
            type: "user",
            title: "用户申诉",
            content: "用户提交产品质量纠纷，要求赔偿",
            operator: "用户",
            evidence: [
              "https://example.com/evidence3.jpg",
              "https://example.com/evidence4.jpg"
            ]
          },
          {
            time: "2024-03-10 18:30:00",
            type: "user",
            title: "用户补充材料",
            content: "用户补充医院诊断证明",
            operator: "用户",
            evidence: ["https://example.com/evidence5.jpg"]
          },
          {
            time: "2024-03-11 09:15:00",
            type: "merchant",
            title: "商家回复",
            content: "商家否认产品质量问题，提供检验报告",
            operator: "商家",
            evidence: [
              "https://example.com/merchant-evidence2.jpg",
              "https://example.com/merchant-evidence3.jpg"
            ]
          },
          {
            time: "2024-03-11 10:20:00",
            type: "admin",
            title: "管理员受理",
            content: "管理员受理纠纷，正在审核相关材料",
            operator: "管理员李经理",
            evidence: []
          }
        ],
        contactName: "李四",
        contactPhone: "13900139002",
        contactEmail: "lisi@example.com",
        merchantName: "贵港特产食品有限公司",
        merchantPhone: "0775-8765432",
        merchantEmail: "food@example.com",
        productName: "贵港特色腐竹"
      },
      {
        id: 3,
        orderNo: "DD202403050003",
        type: "service",
        amount: 680.0,
        status: "processing",
        createTime: "2024-03-05 11:20:00",
        updateTime: "2024-03-06 16:30:00",
        content: "预订的导游服务态度恶劣，提前结束行程，未完成约定的景点游览，要求退款。",
        reason: "服务质量不符",
        evidence: [
          "https://example.com/evidence6.jpg",
          "https://example.com/evidence7.jpg"
        ],
        merchantResponse: {
          opinion: "部分认可",
          content: "因天气原因部分景点关闭，导游调整了行程。认可服务有瑕疵，但并非故意缩短行程，可退还部分费用。",
          evidence: [
            "https://example.com/merchant-evidence4.jpg"
          ]
        },
        processHistory: [
          {
            time: "2024-03-05 11:20:00",
            type: "user",
            title: "用户申诉",
            content: "用户提交服务质量纠纷",
            operator: "用户",
            evidence: [
              "https://example.com/evidence6.jpg",
              "https://example.com/evidence7.jpg"
            ]
          },
          {
            time: "2024-03-06 09:30:00",
            type: "merchant",
            title: "商家回复",
            content: "商家部分认可问题，提出部分退款方案",
            operator: "商家",
            evidence: [
              "https://example.com/merchant-evidence4.jpg"
            ]
          },
          {
            time: "2024-03-06 16:30:00",
            type: "admin",
            title: "管理员受理",
            content: "管理员正在协调双方和解",
            operator: "管理员王主管",
            evidence: []
          }
        ],
        contactName: "王五",
        contactPhone: "13700137003",
        contactEmail: "wangwu@example.com",
        merchantName: "贵港旅游服务有限公司",
        merchantPhone: "0775-5432109",
        merchantEmail: "tour@example.com",
        productName: "贵港一日游导游服务"
      },
      {
        id: 4,
        orderNo: "DD202402280004",
        type: "refund",
        amount: 199.0,
        status: "completed",
        createTime: "2024-02-28 14:30:00",
        updateTime: "2024-03-01 11:15:00",
        content: "因个人原因无法按时参加活动，提前3天申请退款被拒，但商家协议承诺提前48小时可全额退款。",
        reason: "退款政策争议",
        evidence: [
          "https://example.com/evidence8.jpg",
          "https://example.com/evidence9.jpg"
        ],
        merchantResponse: {
          opinion: "否认",
          content: "我们的退款政策是提前72小时申请才能全额退款，48小时内只能退款50%。",
          evidence: [
            "https://example.com/merchant-evidence5.jpg"
          ]
        },
        processHistory: [
          {
            time: "2024-02-28 14:30:00",
            type: "user",
            title: "用户申诉",
            content: "用户提交退款政策纠纷",
            operator: "用户",
            evidence: [
              "https://example.com/evidence8.jpg",
              "https://example.com/evidence9.jpg"
            ]
          },
          {
            time: "2024-02-29 09:20:00",
            type: "merchant",
            title: "商家回复",
            content: "商家否认退款政策有误",
            operator: "商家",
            evidence: [
              "https://example.com/merchant-evidence5.jpg"
            ]
          },
          {
            time: "2024-02-29 14:00:00",
            type: "admin",
            title: "管理员受理",
            content: "管理员已审核双方材料",
            operator: "管理员赵经理",
            evidence: []
          },
          {
            time: "2024-03-01 11:15:00",
            type: "admin",
            title: "仲裁结果",
            content: "经核实，官网确实存在两处不同的退款政策说明，为保障消费者权益，判决商家退款70%",
            operator: "管理员赵经理",
            evidence: [
              "https://example.com/admin-evidence1.jpg"
            ]
          }
        ],
        contactName: "赵六",
        contactPhone: "13600136004",
        contactEmail: "zhaoliu@example.com",
        merchantName: "贵港文化活动策划有限公司",
        merchantPhone: "0775-6543210",
        merchantEmail: "activity@example.com",
        productName: "贵港传统文化体验活动"
      }
    ];
    total.value = arbitrationList.value.length;
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.arbitration-management {
  padding: 20px;
}
</style>
